package com.zhou.util;

import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.IOUtils;

import java.io.*;

@Slf4j
public class PictureUtil {

    public static void main(String[] args) throws Exception{
        byte[] b = IOUtils.toByteArray(new FileInputStream("C:\\Users\\Administrator\\Desktop\\gif\\timg (1).gif"));
        b = PictureUtil.compressPicForScale(b,20);
        FileOutputStream out = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\22.gif");
        out.write(b);
        out.flush();
        out.close();
    }


    /**
     * 根据指定大小压缩图片
     *
     * @param imageBytes  源图片字节数组
     * @param desFileSize 指定图片大小，单位kb
     * @return 压缩质量后的图片字节数组
     */
    public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize) throws Exception{
        long d = desFileSize * 1024;
        if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length <= d) {
            return imageBytes;
        }
        long srcSize = imageBytes.length;
        double accuracy = getAccuracy(srcSize / 1024);
        int cnt = 0;
        while (imageBytes.length > d && cnt < 1000) {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
            Thumbnails.of(inputStream)
                    .scale(accuracy)
                    .outputQuality(accuracy)
                    .toOutputStream(outputStream);
            imageBytes = outputStream.toByteArray();
            cnt++;
        }
        return imageBytes;
    }
    public static byte[] compressPicForScale(byte[] imageBytes, int x,int y,double quality) throws Exception{
        ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
        Thumbnails.of(inputStream)
                .width(x).height(y)
                .outputQuality(quality)
                .toOutputStream(outputStream);
        imageBytes = outputStream.toByteArray();
        return imageBytes;
    }

    /**
     * 自动调节精度(经验数值)
     *
     * @param size 源图片大小
     * @return 图片压缩质量比
     */
    public static double getAccuracy(long size) {
        double accuracy;
        if (size < 900) {
            accuracy = 0.85;
        } else if (size < 2047) {
            accuracy = 0.6;
        } else if (size < 3275) {
            accuracy = 0.44;
        } else {
            accuracy = 0.4;
        }
        return accuracy;
    }

}
